import { Balloon, Icon, Pagination, Table } from '@alifd/next';
import { TableProps } from '@alifd/next/types/table';
import dayjs from 'dayjs';
import { observer } from 'mobx-react-lite';
import React, { useCallback, useEffect, useMemo } from 'react';
import styles from './index.module.scss';

const SORT_DIRS = ['desc', 'asc', 'default'];
function nextDir(dir) {
  const idx = SORT_DIRS.indexOf(dir);
  if (idx === -1) return SORT_DIRS[0];
  return SORT_DIRS[idx + 1];
}

export const widthDefaults = {
  datetime: 124,

}

export const ellipsisRender = (value, index, record) => {
  const intro = (
    <span
      style={{
        overflow: "hidden",
        textOverflow: "ellipsis",
        whiteSpace: "nowrap",
      }}
    >
      {value}
    </span>
  );
  return (
    <Balloon.Tooltip v2 trigger={intro} align="bl" key={_.uniqueId()}>
      {value}
    </Balloon.Tooltip>
  );
};

export const dateTimeRender = (v, index, record) => {
  return ellipsisRender(dayjs(v).format('YYYY-MM-DD HH:mm'), index, record)
  // return dayjs(v).format('YYYY-MM-DD HH:mm:ss');
}

interface TauTableProps extends TableProps {
  instanceId?: string;
  hidePagination?: boolean;
  pageSize?: number;
  total?: number;
  currentPage?: number;
  // onPage?: (value: number) => void;
  // onPageSize?: (value: number) => void;
  onFetch?: (pg: { page?: number, size?: number, sort?: string[] }) => void;
  expandAll?: boolean;
}

function TauTable({
  instanceId,
  dataSource,
  columns,
  hidePagination,
  expandAll,
  pageSize,
  total,
  currentPage,
  // onPage,
  // onPageSize,
  onFetch,
  ...props
}: TauTableProps) {
  const [openKeys, setOpenKeys] = React.useState<string[]>([]);
  const { expandedRowRender, sort } = props;
  const expandable: boolean = useMemo(() => !!expandedRowRender, [expandedRowRender]);
  const [tauColumns, setTauColumns] = React.useState<any[]>(expandable ? [] : columns!);

  const toggleOpen = useCallback((value, index, { id, expandable }) => {
    if (expandable === false) return <></>;
    const expanded = openKeys.includes(id);

    return <ExpandCtrl expanded={expanded} onToggle={() =>
      setOpenKeys((prev) => {
        const idx = prev.indexOf(id);
        if (idx === -1) prev.push(id); else prev.splice(idx, 1);
        return [...prev];
      })
    } />;
  }, [openKeys]);

  useEffect(() => {
    const cols = [...columns!];
    cols.forEach((col) => {
      // if (!col.cell) col.cell = ellipsisRender; // TODO 计算宽度，自动显示Tooltip?
      col.align = col.align || 'center';
      if (col.sortable === true && typeof col.title !== 'function') {
        const fn = col.dataIndex;
        const lastDir = sort?.[fn];
        col.sortDirections = SORT_DIRS;
        col.title = <span style={{ cursor: 'pointer' }} onClick={() => handleSort(fn, nextDir(lastDir))}>{col.title}</span>;
      }
    })
    if (expandable) {
      cols.unshift({
        title: '',
        width: 24,
        cell: toggleOpen,
      });
    }

    setTauColumns(cols);
  }, [expandable, openKeys]);

  useEffect(() => {
    if (expandAll) {
      setOpenKeys(dataSource!.map((row) => row.id));
    } else {
      setOpenKeys([]);
    }
  }, [expandAll, dataSource]);

  const handleSort = (dataIndex, order) => {
    // console.log('sort:', dataIndex, order);
    const expr = order === 'default' ? [] : [`${dataIndex};${order}`];
    onFetch?.({ sort: expr });
  }

  if (tauColumns.length === 0) return <></>;

  const pg = { pageSize, total, current: currentPage! + 1 };
  return (
    <div className={styles.tauTable}>
      <Table.StickyLock
        dataSource={dataSource}
        columns={tauColumns}
        hasBorder={false}
        onSort={handleSort}
        {...props}
        hasExpandedRowCtrl={false}
        expandedIndexSimulate
        openRowKeys={openKeys}
        // sortIcons={{desc: <Icon style={{top: '6px', left: '4px'}} type={'arrow-down'} size="small" />, asc: <Icon style={{top: '-6px', left: '4px'}} type={'arrow-up'} size="small" />}}
      />
      {!hidePagination &&
        <Pagination
          style={{ textAlign: "right" }}
          {...pg}
          totalRender={(total) => <span style={{ marginLeft: 12, color: 'var(--pagination-size-selector-title-color, #999999)' }}>{`共 ${total} 条`}</span>}
          pageSizeList={[10, 20, 50, 100]}
          pageSizeSelector="dropdown"
          onPageSizeChange={(size) => onFetch?.({ size, page: 0 })}
          onChange={(n) => onFetch?.({ page: n - 1 })}
        />}
    </div>
  );
}

const ExpandCtrl = ({ expanded, onToggle }) => {
  return (
    <div style={{ cursor: 'pointer' }} onClick={onToggle} >
      <Icon type={expanded ? 'arrow-down' : 'arrow-right'} size="xxs" />
    </div>
  );
}

export default observer(TauTable);
